package com.fengwk.support.math;

import java.math.BigDecimal;

import com.fengwk.support.function.Return;
import com.fengwk.support.util.MathUtils;

/**
 * 导数函数
 * 
 * @author fengwk
 *
 */
public class DerivedFunction implements Return.Params1<BigDecimal, BigDecimal> {

	private static final long serialVersionUID = 7465533082208636192L;
	
	/**
     * 极限,表示无穷小的Δx
     */
	private final static BigDecimal LIMIT_DELTA = MathUtils.bigDecimal("0.00000000000000000000001");
	private final static BigDecimal LIMIT_DELTA_DOUBLE = MathUtils.mul(LIMIT_DELTA, MathUtils.bigDecimal(2));
	
	private Return.Params1<BigDecimal, BigDecimal> fun;
	
	public DerivedFunction(Return.Params1<BigDecimal, BigDecimal> fun) {
        this.fun = fun;
    }
	
	@Override
	public BigDecimal apply(BigDecimal x) {
		// 综合左右导数
		return MathUtils.div(MathUtils.distance(fun.apply(MathUtils.sub(x, LIMIT_DELTA)), fun.apply(MathUtils.add(x, LIMIT_DELTA))), LIMIT_DELTA_DOUBLE);
    }
	
}